<template>
  <view class="coupon-search-page">
    <!-- 导航栏 -->
    <NavBar title="搜索优惠券" />

    <!-- 搜索框 -->
    <view class="search-box">
      <nut-input
        v-model="keyword"
        placeholder="搜索优惠券名称、商品类别"
        clearable
        @clear="clearSearch"
      >
        <template #right>
          <nut-button size="small" type="primary" @click="searchCoupons">搜索</nut-button>
        </template>
      </nut-input>
    </view>

    <!-- 筛选条件 -->
    <view class="filter-box">
      <view class="filter-title">筛选条件</view>
      <view class="filter-options">
        <view class="filter-item">
          <view class="filter-label">优惠券状态</view>
          <view class="filter-value">
            <nut-radio-group v-model="status" direction="horizontal">
              <nut-radio label="all">全部</nut-radio>
              <nut-radio label="unused">未使用</nut-radio>
              <nut-radio label="used">已使用</nut-radio>
              <nut-radio label="expired">已过期</nut-radio>
            </nut-radio-group>
          </view>
        </view>
        <view class="filter-item">
          <view class="filter-label">优惠券类型</view>
          <view class="filter-value">
            <nut-radio-group v-model="couponType" direction="horizontal">
              <nut-radio label="all">全部</nut-radio>
              <nut-radio label="general">通用券</nut-radio>
              <nut-radio label="category">品类券</nut-radio>
            </nut-radio-group>
          </view>
        </view>
      </view>
      <view class="filter-actions">
        <nut-button size="small" @click="resetFilters">重置</nut-button>
        <nut-button size="small" type="primary" @click="applyFilters">确定</nut-button>
      </view>
    </view>

    <!-- 搜索结果 -->
    <view class="search-result">
      <!-- 空结果提示 -->
      <nut-empty v-if="couponList.length === 0" description="暂无符合条件的优惠券" image="empty">
        <template #footer>
          <nut-button type="primary" size="small" @click="goCouponCenter">去领券中心</nut-button>
        </template>
      </nut-empty>

      <!-- 优惠券列表 -->
      <view v-else class="coupon-list">
        <view 
          v-for="(item, index) in couponList" 
          :key="index"
          class="coupon-item"
          :class="{
            'used': item.status === 'used',
            'expired': item.status === 'expired'
          }"
          @click="viewCouponDetail(item)"
        >
          <view class="coupon-left">
            <view class="coupon-amount">
              <text class="symbol">¥</text>
              <text class="value">{{ item.amount }}</text>
            </view>
            <view class="coupon-condition">满{{ item.minAmount }}元可用</view>
          </view>
          <view class="coupon-right">
            <view class="coupon-name">{{ item.name }}</view>
            <view class="coupon-scope">{{ item.scope }}</view>
            <view class="coupon-time">{{ item.validTimeDesc }}</view>
            <view class="coupon-status" v-if="item.status !== 'unused'">
              <image 
                :src="item.status === 'used' ? usedStamp : expiredStamp" 
                class="status-stamp"
              />
            </view>
          </view>
          <view class="coupon-circle-top"></view>
          <view class="coupon-circle-bottom"></view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import NavBar from '@/components/NavBar/index.vue'
import userApi from '@/api/user'
import type { CouponItem } from '@/api/types'
import { useLoading } from '@/hooks/useLoading'

// 搜索关键词
const keyword = ref('')

// 筛选条件
const status = ref('all')
const couponType = ref('all')

// 优惠券列表
const couponList = ref<CouponItem[]>([])

// 加载状态
const { loading, showLoading, hideLoading } = useLoading()

// 状态图片
const usedStamp = 'https://img01.yzcdn.cn/vant/coupon-used.png'
const expiredStamp = 'https://img01.yzcdn.cn/vant/coupon-expired.png'

// 搜索优惠券
const searchCoupons = async () => {
  try {
    showLoading('搜索中...')
    
    // 调用API获取优惠券列表
    const res = await userApi.getCouponList({
      status: status.value === 'all' ? undefined : status.value
    })
    
    // 根据关键词和筛选条件过滤优惠券
    couponList.value = res.data.filter((coupon: CouponItem) => {
      // 关键词匹配
      const keywordMatch = !keyword.value || 
        coupon.name.toLowerCase().includes(keyword.value.toLowerCase()) || 
        coupon.scope.toLowerCase().includes(keyword.value.toLowerCase())
      
      // 优惠券类型匹配
      const typeMatch = couponType.value === 'all' || 
        (couponType.value === 'general' && !coupon.categoryId) || 
        (couponType.value === 'category' && coupon.categoryId)
      
      return keywordMatch && typeMatch
    })
  } catch (error) {
    console.error('搜索优惠券失败', error)
    
    // 模拟数据
    couponList.value = [
      {
        id: '1',
        name: '新人专享券',
        amount: '10',
        minAmount: '100',
        scope: '全场通用',
        categoryId: '',
        validTimeDesc: '2023-06-01 ~ 2023-07-01',
        status: 'unused'
      },
      {
        id: '2',
        name: '满减优惠券',
        amount: '50',
        minAmount: '300',
        scope: '全场通用',
        categoryId: '',
        validTimeDesc: '2023-06-01 ~ 2023-07-01',
        status: 'unused'
      }
    ].filter(coupon => {
      // 关键词匹配
      const keywordMatch = !keyword.value || 
        coupon.name.toLowerCase().includes(keyword.value.toLowerCase()) || 
        coupon.scope.toLowerCase().includes(keyword.value.toLowerCase())
      
      // 优惠券类型匹配
      const typeMatch = couponType.value === 'all' || 
        (couponType.value === 'general' && !coupon.categoryId) || 
        (couponType.value === 'category' && coupon.categoryId)
      
      // 状态匹配
      const statusMatch = status.value === 'all' || coupon.status === status.value
      
      return keywordMatch && typeMatch && statusMatch
    })
    
    Taro.showToast({
      title: '搜索优惠券失败',
      icon: 'none'
    })
  } finally {
    hideLoading()
  }
}

// 清空搜索
const clearSearch = () => {
  keyword.value = ''
  searchCoupons()
}

// 重置筛选条件
const resetFilters = () => {
  status.value = 'all'
  couponType.value = 'all'
}

// 应用筛选条件
const applyFilters = () => {
  searchCoupons()
}

// 查看优惠券详情
const viewCouponDetail = (coupon: CouponItem) => {
  Taro.navigateTo({
    url: `/pages/coupon/detail?id=${coupon.id}`
  })
}

// 去领券中心
const goCouponCenter = () => {
  Taro.navigateTo({
    url: '/pages/coupon/center'
  })
}

// 组件挂载时初始化
onMounted(() => {
  searchCoupons()
})
</script>

<style lang="scss" scoped>
.coupon-search-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 20px;
  
  .search-box {
    padding: 10px;
    background-color: #fff;
    margin-bottom: 10px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    
    :deep(.nut-input) {
      --nut-input-border-bottom: none;
    }
  }
  
  .filter-box {
    padding: 15px;
    background-color: #fff;
    margin-bottom: 10px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    
    .filter-title {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 10px;
      color: #333;
    }
    
    .filter-options {
      .filter-item {
        margin-bottom: 15px;
        
        .filter-label {
          font-size: 14px;
          color: #666;
          margin-bottom: 8px;
        }
        
        .filter-value {
          :deep(.nut-radio) {
            margin-right: 15px;
          }
        }
      }
    }
    
    .filter-actions {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      margin-top: 15px;
    }
  }
  
  .search-result {
    padding: 10px;
    
    .coupon-list {
      .coupon-item {
        position: relative;
        display: flex;
        margin-bottom: 15px;
        height: 100px;
        background: linear-gradient(to right, #fa2c19, #fa6419);
        border-radius: 8px;
        color: #fff;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(250, 44, 25, 0.2);
        transition: all 0.3s ease;
        
        &:active {
          transform: scale(0.98);
          opacity: 0.9;
        }
        
        &.used,
        &.expired {
          background: linear-gradient(to right, #999, #aaa);
          box-shadow: 0 2px 8px rgba(153, 153, 153, 0.2);
          
          &:active {
            transform: none;
            opacity: 1;
          }
        }
        
        .coupon-left {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          width: 120px;
          border-right: 1px dashed rgba(255, 255, 255, 0.3);
          
          .coupon-amount {
            display: flex;
            align-items: baseline;
            
            .symbol {
              font-size: 16px;
              margin-right: 2px;
            }
            
            .value {
              font-size: 30px;
              font-weight: bold;
            }
          }
          
          .coupon-condition {
            font-size: 12px;
            margin-top: 5px;
          }
        }
        
        .coupon-right {
          flex: 1;
          padding: 15px;
          position: relative;
          
          .coupon-name {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 5px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 180px;
          }
          
          .coupon-scope {
            font-size: 12px;
            margin-bottom: 5px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 180px;
          }
          
          .coupon-time {
            font-size: 12px;
            opacity: 0.8;
          }
          
          .coupon-status {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%) rotate(-15deg);
            
            .status-stamp {
              width: 60px;
              height: 60px;
              opacity: 0.8;
            }
          }
        }
        
        .coupon-circle-top,
        .coupon-circle-bottom {
          position: absolute;
          left: 110px;
          width: 20px;
          height: 20px;
          background-color: #f5f5f5;
          border-radius: 50%;
        }
        
        .coupon-circle-top {
          top: -10px;
        }
        
        .coupon-circle-bottom {
          bottom: -10px;
        }
      }
    }
  }
  
  :deep(.nut-empty) {
    padding: 40px 0;
  }
}
</style>